/*
ESP32-CAM PIR人體移動感測器啟動影像上傳Google試算表
Author : ChungYi Fu (Kaohsiung, Taiwan)  2021-6-30 00:00
https://www.facebook.com/francefu

PIR人體移動感測器 -> GND, IO13, 3.3V

Google試算表
https://docs.google.com/spreadsheets/u/0/

Google Script管理介面
https://script.google.com/home
https://script.google.com/home/executions

Google Script程式碼

function doPost(e) {
  var myFile = e.parameter.myFile;  //取得影像檔
  var myFilename = Utilities.formatDate(new Date(), "GMT", "yyyyMMddHHmmss")+"_"+e.parameter.myFilename;  //取得影像檔名
  var mySpreadsheetId = e.parameter.mySpreadsheetId;  //試算表Id
  var myCellRow = e.parameter.myCellRow;   //取得插入影像儲存格Row
  var myCellCol = e.parameter.myCellCol;   //取得插入影像儲存格Col 
  
  var contentType = myFile.substring(myFile.indexOf(":")+1, myFile.indexOf(";"));
  var data = myFile.substring(myFile.indexOf(",")+1);
  data = Utilities.base64Decode(data);
  var blob = Utilities.newBlob(data, contentType, myFilename);

  var ss = SpreadsheetApp.openById(mySpreadsheetId);
  ss.getActiveSheet().setHiddenGridlines(true);
  var sheet = ss.getSheets()[0];
  sheet.insertImage(blob, myCellRow, myCellCol);

  var images = sheet.getImages();
  while (images.length>2) {   //影像數超過兩張即刪除最早影像，僅保留最新兩張影像
    images[0].remove();
  }
     
  return  ContentService.createTextOutput("ok");
}

*/

//輸入Wi-Fi帳密
const char* ssid     = "teacher";    //Wi-Fi帳號
const char* password = "87654321";   //Wi-Fi密碼
int pinPIR = 13;   //PIR人體移動感測器腳位
String myScript = "/macros/s/**********ID**********/exec";    //設定Google Script路徑
String myFilename = "&myFilename=ESP32-CAM.jpg";
String myImage = "&myFile=";

//How to get Spreadsheet ID from spreadsheet url?  
//https://docs.google.com/spreadsheets/d/**********ID**********/edit#gid=0
String mySpreadsheetId = "&mySpreadsheetId=**********ID**********";  //設定Google試算表ID

String myCellRow = "&myCellRow=1";
String myCellCol = "&myCellCol=1";

#include <WiFi.h>
#include <WiFiClientSecure.h>
#include "soc/soc.h"
#include "soc/rtc_cntl_reg.h"
#include "Base64.h"  //不可使用Arduino IDE內建的函式庫，請從github下載Base64.cpp, Base64.h置於同一資料夾
#include "esp_camera.h"

//Arduino IDE開發版選擇 ESP32 Wrover Module

//ESP32-CAM 安信可模組腳位設定
#define PWDN_GPIO_NUM     32
#define RESET_GPIO_NUM    -1
#define XCLK_GPIO_NUM      0
#define SIOD_GPIO_NUM     26
#define SIOC_GPIO_NUM     27
#define Y9_GPIO_NUM       35
#define Y8_GPIO_NUM       34
#define Y7_GPIO_NUM       39
#define Y6_GPIO_NUM       36
#define Y5_GPIO_NUM       21
#define Y4_GPIO_NUM       19
#define Y3_GPIO_NUM       18
#define Y2_GPIO_NUM        5
#define VSYNC_GPIO_NUM    25
#define HREF_GPIO_NUM     23
#define PCLK_GPIO_NUM     22

void setup()
{
  WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0);  //關閉電源不穩就重開機的設定
    
  Serial.begin(115200);
  Serial.setDebugOutput(true);  //開啟診斷輸出
  Serial.println();

  camera_config_t config;
  config.ledc_channel = LEDC_CHANNEL_0;
  config.ledc_timer = LEDC_TIMER_0;
  config.pin_d0 = Y2_GPIO_NUM;
  config.pin_d1 = Y3_GPIO_NUM;
  config.pin_d2 = Y4_GPIO_NUM;
  config.pin_d3 = Y5_GPIO_NUM;
  config.pin_d4 = Y6_GPIO_NUM;
  config.pin_d5 = Y7_GPIO_NUM;
  config.pin_d6 = Y8_GPIO_NUM;
  config.pin_d7 = Y9_GPIO_NUM;
  config.pin_xclk = XCLK_GPIO_NUM;
  config.pin_pclk = PCLK_GPIO_NUM;
  config.pin_vsync = VSYNC_GPIO_NUM;
  config.pin_href = HREF_GPIO_NUM;
  config.pin_sscb_sda = SIOD_GPIO_NUM;
  config.pin_sscb_scl = SIOC_GPIO_NUM;
  config.pin_pwdn = PWDN_GPIO_NUM;
  config.pin_reset = RESET_GPIO_NUM;
  config.xclk_freq_hz = 20000000;
  config.pixel_format = PIXFORMAT_JPEG;
  
  //
  // WARNING!!! PSRAM IC required for UXGA resolution and high JPEG quality
  //            Ensure ESP32 Wrover Module or other board with PSRAM is selected
  //            Partial images will be transmitted if image exceeds buffer size
  //   
  // if PSRAM IC present, init with UXGA resolution and higher JPEG quality
  //                      for larger pre-allocated frame buffer.
  if(psramFound()){  //是否有PSRAM(Psuedo SRAM)記憶體IC
    config.frame_size = FRAMESIZE_UXGA;
    config.jpeg_quality = 10;
    config.fb_count = 2;
  } else {
    config.frame_size = FRAMESIZE_SVGA;
    config.jpeg_quality = 12;
    config.fb_count = 1;
  }

  //視訊初始化
  esp_err_t err = esp_camera_init(&config);
  if (err != ESP_OK) {
    Serial.printf("Camera init failed with error 0x%x", err);
    ESP.restart();
  }

  //可自訂視訊框架預設大小(解析度大小)
  sensor_t * s = esp_camera_sensor_get();
  // initial sensors are flipped vertically and colors are a bit saturated
  if (s->id.PID == OV3660_PID) {
    s->set_vflip(s, 1); // flip it back
    s->set_brightness(s, 1); // up the brightness just a bit
    s->set_saturation(s, -2); // lower the saturation
  }
  // drop down frame size for higher initial frame rate
  s->set_framesize(s, FRAMESIZE_QVGA);    //解析度 UXGA(1600x1200), SXGA(1280x1024), XGA(1024x768), SVGA(800x600), VGA(640x480), CIF(400x296), QVGA(320x240), HQVGA(240x176), QQVGA(160x120), QXGA(2048x1564 for OV3660)

  //s->set_vflip(s, 1);  //垂直翻轉
  //s->set_hmirror(s, 1);  //水平鏡像

  //閃光燈(GPIO4)
  ledcAttachPin(4, 4);  
  ledcSetup(4, 5000, 8);
  
  WiFi.mode(WIFI_STA);
  
  for (int i=0;i<2;i++) {
    WiFi.begin(ssid, password);    //執行網路連線
  
    delay(1000);
    Serial.println("");
    Serial.print("Connecting to ");
    Serial.println(ssid);
    
    long int StartTime=millis();
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        if ((StartTime+5000) < millis()) break;    //等待10秒連線
    } 
  
    if (WiFi.status() == WL_CONNECTED) {    //若連線成功
      Serial.println("");
      Serial.println("STAIP address: ");
      Serial.println(WiFi.localIP());
      Serial.println("");
  
      for (int i=0;i<5;i++) {   //若連上WIFI設定閃光燈快速閃爍
        ledcWrite(4,10);
        delay(200);
        ledcWrite(4,0);
        delay(200);    
      }
  
      break;
    }
  } 

  if (WiFi.status() != WL_CONNECTED) {  //若連線失敗
    ESP.restart();  //重啟電源
  } 
          
  //閃光燈(GPIO4)
  ledcAttachPin(4, 4);  
  ledcSetup(4, 5000, 8);
  
  //測試傳送影像至Google試算表
  Serial.println(SendCapturedImage2Spreadsheet());
  
  pinMode(pinPIR, INPUT_PULLUP);  //設定上拉電阻
}

void loop()
{
  int v = digitalRead(pinPIR);
  Serial.println(v);
  if (v==1) {
    SendCapturedImage2Spreadsheet();
    //Serial.println(SendCapturedImage2Spreadsheet());  //取回傳送結果輸出序列埠
    delay(5000);  //視延遲時間設定，最小為5秒
  }
  else
    delay(1000);
}

String SendCapturedImage2Spreadsheet() {
  const char* myDomain = "script.google.com";  
  String getAll="", getBody = "";

  camera_fb_t * fb = NULL;
  fb = esp_camera_fb_get();  
  if(!fb) {
    Serial.println("Camera capture failed");
    delay(1000);
    ESP.restart();
  }
        
  Serial.println("Connect to " + String(myDomain));
  WiFiClientSecure client_tcp;
  client_tcp.setInsecure();   //run version 1.0.5 or above
  
  if (client_tcp.connect(myDomain, 443)) {
    Serial.println("Connection successful");
        
      char *input = (char *)fb->buf;
      char output[base64_enc_len(3)];
      String imageFile = "data:image/jpeg;base64,";
      for (int i=0;i<fb->len;i++) {
        base64_encode(output, (input++), 3);
        if (i%3==0) imageFile += urlencode(String(output));
      }
      String Data = myFilename+mySpreadsheetId+myCellRow+myCellCol+myImage;
      
      client_tcp.println("POST " + myScript + " HTTP/1.1");
      client_tcp.println("Host: " + String(myDomain));
      client_tcp.println("Content-Length: " + String(Data.length()+imageFile.length()));
      client_tcp.println("Content-Type: application/x-www-form-urlencoded");
      client_tcp.println("Connection: keep-alive");
      client_tcp.println();
      
      client_tcp.print(Data);
      int Index;
      for (Index = 0; Index < imageFile.length(); Index = Index+1000) {
        client_tcp.print(imageFile.substring(Index, Index+1000));
      }
      esp_camera_fb_return(fb);
      
      int waitTime = 5000;   // timeout 10 seconds
      long startTime = millis();
      boolean state = false;
      
      while ((startTime + waitTime) > millis()) {
        delay(100);      
        while (client_tcp.available()) {
            char c = client_tcp.read();
            if (state==true) getBody += String(c);          
            if (c == '\n') {
              if (getAll.length()==0) state=true; 
              getAll = "";
            } else if (c != '\r')
              getAll += String(c);
            startTime = millis();
         }
         if (getBody.length()>0) break;
      }
      client_tcp.stop();
      Serial.println(getBody);
  }
  else {
    Serial.println("Connected to " + String(myDomain) + " failed.");
    return "Connected to " + String(myDomain) + " failed.";
  }
  return getBody;
}

//https://www.arduino.cc/reference/en/libraries/urlencode/
String urlencode(String str) {
  const char *msg = str.c_str();
  const char *hex = "0123456789ABCDEF";
  String encodedMsg = "";
  while (*msg != '\0') {
    if (('a' <= *msg && *msg <= 'z') || ('A' <= *msg && *msg <= 'Z') || ('0' <= *msg && *msg <= '9') || *msg == '-' || *msg == '_' || *msg == '.' || *msg == '~') {
      encodedMsg += *msg;
    } else {
      encodedMsg += '%';
      encodedMsg += hex[(unsigned char)*msg >> 4];
      encodedMsg += hex[*msg & 0xf];
    }
    msg++;
  }
  return encodedMsg;
}
